//
//  DiaryEditViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/12/8.
//

import UIKit

@objc protocol DiaryEditViewControllerDelegate: class {
    func diaryEditDone(dic: NSDictionary?, editIndex: Int,attriStr:NSAttributedString?)
}

@objcMembers
class DiaryEditViewController: UIViewController,AddDiaryContentViewControllerDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var btn: UIButton!
    
    var tempAttr:NSAttributedString?
    
    public var dic: [String: Any]? {
        didSet {
//            selectArray = dic?["reasonArray"] as? [String]
            
            let timeStampStr: String? = dic?["timeStampStr"] as? String
            let navTitle = NSString.convertTimeStamp(toMH: timeStampStr ?? "")
            navigationItem.title = navTitle
        }
    }
    
    var isOpen = false
    
    var selectArray: [String]?
    
    var editIndex = -1 // 编辑的那一条数据，为DiaryForDayController使用
    
    weak var delegate: DiaryEditViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        selectArray = dic?["reasonArray"] as? [String]
        
        btn.layer.cornerRadius = btn.height * 0.5
        btn.layer.borderWidth = 1.0
        btn.layer.borderColor = UIColor.hexColor(hex: "#E0E0E0").cgColor
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "完成编辑"), style: .plain, target: self, action: #selector(action(_:)))
        
        NotificationCenter.default.addObserver(self, selector: #selector(endEditNotifitionAction), name: Notification.Name("endEditNotifition"), object: nil)
        
        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillShowNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
            
            guard let self = self else { return }
            let noti: Notification = x as! Notification
            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
            UIView.animate(withDuration: time) {
                self.view.transform = CGAffineTransform.identity
            }
            var maxHeight = 200.0 + 210.0 + 150.0
            maxHeight += (self.isOpen == true) ? 460.0 : 160.0
            let textFieldMaxY = maxHeight + statusAndNav_height
            let keyBoardMinY = (noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect).origin.y
            let distance = textFieldMaxY - Double(keyBoardMinY)
            if distance > 0 {
                UIView.animate(withDuration: time) {
                    self.view.frame = CGRect.init(x: 0, y: CGFloat(-distance - 25.0), width: self.view.width, height: self.view.height)
//                    self.view.transform = CGAffineTransform.init(translationX: 0, y: CGFloat(-distance - 25.0))
//                    self.tableView.scrollToRow(at: IndexPath(row: 3, section: 0), at: .bottom, animated: true)
                }
            }
        })
        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillHideNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
            
            guard let self = self else { return }

            let noti: Notification = x as! Notification
            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
            UIView.animate(withDuration: time) {
                self.view.frame = CGRect.init(x: 0, y: 0, width: self.view.width, height: self.view.height)
//                self.view.transform = CGAffineTransform.init(translationX: 0, y: 0)
            }
        })
        
    }
    
    @objc func endEditNotifitionAction() {
        view.endEditing(true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

    @objc @IBAction func action(_ sender: Any) {
        view.endEditing(true)
        
//        if let cell: DiaryEditReasonDetailTableViewCell = tableView.cellForRow(at: IndexPath(row: 3, section: 0)) as? DiaryEditReasonDetailTableViewCell {

//            dic?["reasonDetailStr"] = cell.textView.text
//        }
        

        dic?["reasonArray"] = selectArray
        
        delegate?.diaryEditDone(dic: dic as NSDictionary?, editIndex: self.editIndex,attriStr: tempAttr)
        
        navigationController?.popViewController(animated: true)
        
        // 发送保存通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "editDiaryCompleted"), object: nil)
    }
    
    func attributeEditDone(dict: NSDictionary?, attriStr: NSAttributedString?) {
        
        delegate?.diaryEditDone(dic: dict, editIndex: self.editIndex , attriStr: attriStr)
        
        // 发送保存通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "editDiaryCompleted"), object: nil)
        
    }
    func attriButeEditing(attriStr: NSAttributedString?) {
        
        tempAttr = attriStr
        
        tableView.reloadData()
    }
    
}


extension DiaryEditViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 5 }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 200.0
        }
        if indexPath.row == 1 {
            return 210.0
        }
        if indexPath.row == 2 {
            if isOpen == true {
                
                let marginX: CGFloat = 20.0
                let itemWidth: CGFloat = (CGFloat(view.width - 30.0 * 2) - marginX * 6.0) / 5.0
                let itemHeight: CGFloat = itemWidth - 5.0 + 30.0 + 20.0
                
                let lines = 42 / 5 + (42 % 5 == 0 ? 0 : 1)
                
                return itemHeight * CGFloat(lines) + 50.0 + 30.0 + 50.0 + 30.0
            }
            return 160.0
        }
        if indexPath.row == 3{
            
            let reasonDetailStr = dic?["reasonDetailStr"] as! String
            if (reasonDetailStr.contains("isAttributedString")) {
                
                let fileManager = FileManager.default
                let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String

                let folderPath = docPath + "/" + (dic?["timeStampStr"] as! String) + ".txt"
                
                if let data:Data = fileManager.contents(atPath: folderPath){
                
                    do {
                        let attr = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
                        
                        var height = attr?.string.boundingRect(with: CGSize(width: AppWidth - 30.0*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)], context: nil).size.height ?? 80
                        if tempAttr != nil{
                            
                            height = tempAttr?.string.boundingRect(with: CGSize(width: AppWidth - 30.0*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)], context: nil).size.height ?? 80
                        }
                        
                        return 110+height
                    } catch {
                        
                        print(error)
                        return 110
                    }
                }
            }else{
                
                return 110
            }
            
        }

        return 150

    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell: DiaryEditWeatherTableViewCell = Bundle.main.loadNibNamed("DiaryEditWeatherTableViewCell", owner: self, options: nil)?.last as! DiaryEditWeatherTableViewCell
            cell.selectWeather = dic?["weatherStr"] as? String
            cell.delegate = self
            return cell
            
        }
        if indexPath.row == 1 {
            let cell: DiaryEditMoodTableViewCell = Bundle.main.loadNibNamed("DiaryEditMoodTableViewCell", owner: self, options: nil)?.last as! DiaryEditMoodTableViewCell
            cell.selectMood = dic?["moodStr"] as? String
            cell.delegate = self
            return cell
            
        }
        if indexPath.row == 2 {
            let cell: DiaryEditReasonTableViewCell = Bundle.main.loadNibNamed("DiaryEditReasonTableViewCell", owner: self, options: nil)?.last as! DiaryEditReasonTableViewCell
            cell.label.text = "哪件事让你\(dic?["moodStr"] ?? "")呢?"
            cell.delegate = self
            cell.isOpen = isOpen
            cell.selectArray = selectArray
            return cell
        }
        if indexPath.row == 3 {
            let cell: DiaryEditReasonDetailTableViewCell = Bundle.main.loadNibNamed("DiaryEditReasonDetailTableViewCell", owner: self, options: nil)?.last as! DiaryEditReasonDetailTableViewCell
            
            let reasonDetailStr = dic?["reasonDetailStr"] as! String
            if (reasonDetailStr.contains("isAttributedString")) {
                
                let fileManager = FileManager.default
                let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String

                let folderPath = docPath + "/" + (dic?["timeStampStr"] as! String) + ".txt"
                
                if let data:Data = fileManager.contents(atPath: folderPath){
                
                    do {
                        var attr = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
                        if tempAttr != nil{
                            attr = tempAttr
                        }else{
                            tempAttr = attr
                        }
                        
                        let tempStr = attr?.string.trimmingCharacters(in: NSCharacterSet.newlines)
                        cell.textView.text = tempStr
                    } catch {
                        
                        print(error)
                    }
                }
            }else{
                cell.textView.text = reasonDetailStr
            }
                    
            return cell
        }
        if indexPath.row == 4 {
            
            let cell: DiaryEditPhotosTableViewCell = Bundle.main.loadNibNamed("DiaryEditPhotosTableViewCell", owner: self, options: nil)?.last as! DiaryEditPhotosTableViewCell
            
            let reasonDetailStr = dic?["reasonDetailStr"] as! String
            if (reasonDetailStr.contains("isAttributedString")) {
                
                let fileManager = FileManager.default
                let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String

                let folderPath = docPath + "/" + (dic?["timeStampStr"] as! String) + ".txt"
                
                if let data:Data = fileManager.contents(atPath: folderPath){
                
                    do {
                        var attr = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
                        if tempAttr != nil{
                            attr = tempAttr
                        }else{
                            tempAttr = attr
                        }
                        var imgArr = Array<UIImage>()
                        
                        attr!.enumerateAttributes(in: NSMakeRange(0, attr!.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in
                            
                            if let textAtt:NSTextAttachment = object[NSAttributedString.Key(rawValue: "NSAttachment")] as? NSTextAttachment {
                                
                                let tempImage:UIImage = textAtt.image!;
                                
                                imgArr.append(tempImage)
                            }
                        }
                        
                        cell.photoArr = imgArr
                    } catch {
                        
                        print(error)
                    }
                }
            }
            return cell
        }
        
        return UITableViewCell()
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 3 || indexPath.row == 4{
            
//            var model:DiaryModel = DiaryModel.init()
//            model.timeStampStr = dic?["timeStampStr"] as? String
//            model.createTimeStampStr = dic?["createTimeStampStr"] as? String
//            model.weatherStr = dic?["weatherStr"] as? String
//            model.moodStr = dic?["moodStr"] as? String
//            model.reasonArray = dic?["reasonArray"] as? Array
//            model.reasonDetailStr = dic?["reasonDetailStr"] as? String

            dic?["reasonArray"] = selectArray
            
            let editAttributesContentVC = AddDiaryContentViewController.init()
            editAttributesContentVC.pageType = .typeEdit
            editAttributesContentVC.diaryDict = dic
            editAttributesContentVC.delegate = self
            editAttributesContentVC.tempAttrStr = tempAttr
            navigationController?.pushViewController(editAttributesContentVC, animated: true)
        }else{
            view.endEditing(true)
        }
        
    }
    
}

extension DiaryEditViewController: DiaryEditReasonTableViewCellDelegate {
    
    func diaryEditReason(isOpen: Bool?, selectArray: [String]?) {
        
        if isOpen != nil {
            self.isOpen = isOpen!
        }
        
        self.selectArray = selectArray
        tableView.reloadData()
        
    }
    
}

extension DiaryEditViewController: DiaryEditWeatherTableViewCellDeleagte {
    func diaryEditWeather(weather: String) {
//        dic?.setValue(weather, forKey: "weatherStr")
        dic?["weatherStr"] = weather
    }
}


extension DiaryEditViewController: DiaryEditMoodTableViewCellDeleagte {
    func diaryEditMood(mood: String) {

        dic?["moodStr"] = mood
        
        tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .none)
    }
}
